package main

import (
	"ginmin/configs"
	"ginmin/configs/drivers"
	"ginmin/routes"
	"ginmin/server"
	"os"

	"github.com/gin-gonic/gin"
)

var HttpServer *gin.Engine

func main() {
	// 服务停止时清理数据库链
	defer func() {
		drivers.MysqlDb.Close()
		drivers.RedisDb.Close()
	}()

	// 启动服务
	Run(HttpServer)
}

func Run(httpServer *gin.Engine) {
	// 服务配置
	serverConfig := configs.GetServerConfig()

	// gin 运行时 release debug test
	gin.SetMode(serverConfig["ENV"])
	gin.ForceConsoleColor()
	//捕获错误并记录
	if serverConfig["LogError"] == "1" {
		fErr, err := os.Open("tmp/ginmin_err.log")
		defer func() { fErr.Close() }()
		if err != nil && os.IsNotExist(err) {
			fErr, _ = os.Create("tmp/ginmin_err.log")
		}
		httpServer = gin.New()
		httpServer.Use(gin.RecoveryWithWriter(fErr))
	} else {
		httpServer = gin.Default()
	}
	httpServer.SetTrustedProxies([]string{serverConfig["HOST"]})

	// 配置视图
	if "" != serverConfig["VIEWS_PATTERN"] {
		httpServer.LoadHTMLGlob(serverConfig["VIEWS_PATTERN"])
	}

	// 注册路由
	routes.RegisterRoutes(httpServer)

	//定时任务
	server.TaskStart(serverConfig)

	serverAddr := serverConfig["HOST"] + ":" + serverConfig["PORT"]

	// 启动服务
	err := httpServer.Run(serverAddr)

	if nil != err {
		panic("server run error: " + err.Error())
	}
}
